<template>
	<view style="width: 100%;height: 100vh;display: flex;flex-direction: column;justify-content: space-between;">
		<view style="padding: 0 20rpx;">
			<view class="cell">
				<view class="cell-item" style="width: 100%;">
					<text>条码:</text>
					<input type="text" :disabled="true" v-model="tm" />
				</view>
			</view>
			<view class="cell">
				<view class="cell-item">
					<text>货号:</text>
					<input type="text" :disabled="true" v-model="bbreed" />
				</view>
				<view class="cell-item">
					<text>颜色:</text>
					<input type="text" :disabled="true" v-model="color" />
				</view>
			</view>
			<view class="cell">
				<view class="cell-item">
					<text>尺码:</text>
					<input type="text" :disabled="true" v-model="chima" />
				</view>
				<view class="cell-item">
					<text>数量:</text>
					<input type="number" :disabled="true" v-model="sl" />
				</view>
			</view>
			<view style="margin: auto;width: 90%;">
				<button size="mini" type="primary" :disabled="saveFlag"  style="color: #fff;width: 100%;height: 80rpx;line-height: 80rpx;" @tap="save">确定</button>
			</view>
		</view>
		<view class="btminfo" style="overflow: auto;flex: 1;">
			<t-table style='width: 100%;z-index: 10;'>
				<t-tr>
					<t-td style="flex: 0 0 120upx;word-break: break-word;">货号</t-td>
					<t-td style="flex: 0 0 120upx;word-break: break-word;">颜色</t-td>
					<t-td style="flex: 0 0 100upx;word-break: break-word;">尺码</t-td>
					<t-td style="flex: 0 0 100upx;word-break: break-word;">数量</t-td>
					<t-td style="flex: 1;word-break: break-word;">条码</t-td>
				</t-tr>
				<t-tr v-for="(item,index) in arr" :key="index">
					<t-td style="flex: 0 0 120upx;word-break: break-word;">{{item.bbreed}}</t-td>
					<t-td style="flex: 0 0 120upx;word-break: break-word;">{{item.color}}</t-td>
					<t-td style="flex: 0 0 100upx;word-break: break-word;">{{item.chima}}</t-td>
					<t-td style="flex: 0 0 100upx;word-break: break-word;">{{item.sl}}</t-td>
					<t-td style="flex: 1;word-break: break-word;">{{item.barcode}}</t-td>
				</t-tr>
			</t-table>
		</view>
		<view style="display: flex;align-items: center;justify-content: space-between;height: 100rpx;border-top: 1px solid #ccc;">
			<view style="text-align: center;color: #f0301f;font-size: 40upx;margin-left: 20rpx;">
				已扫描{{sum}}个条码
			</view>
			<view style="width: 50%;display: flex;align-items: center;">
				<button size="mini" type="primary"  style="color: #fff;width: 80%;height: 80rpx;line-height: 80rpx;" @tap="saveInfo">打印</button>
			</view>
		</view>
		<scanCode></scanCode>
		<kk-printer style="position: fixed;left: 10000px;" ref="kkprinter" :bufferData="bufferData" ></kk-printer>
	</view>
</template>


<script>
	import scanCode from '@/static/scan-code/scan-code.vue';
	// import Voice from '@/static/voice.js'; //语音文件
	import axios from '@/static/axios.js';
	import tTable from '@/static/t-table/t-table.vue'
	import tTh from '@/static/t-table/t-th.vue'
	import tTr from '@/static/t-table/t-tr.vue'
	import tTd from '@/static/t-table/t-td.vue'
	const TTSSpeech = uni.requireNativePlugin("MT-TTS-Speech");
	import * as blesdk from '@/components/kk-printer/utils/bluetoolth.js';
	import kkPrinter from '@/components/kk-printer/index.vue';
	var app = getApp();
	import tsc from "@/utils/tsc.js";
	export default {
		components: {
			kkPrinter,
			scanCode,
			tTable,
			tTh,
			tTr,
			tTd
		},
		data() {
			return {
				tm: '',
				num: 0,
				arr: [],
				sl: '',
				color: '',
				chima: '',
				bbreed: '',
				url: '',
				chuanghao: '',
				jhh: '',
				jhhArr: [],
				uid: '',
				uname: '',
				temp: [],
				isShow: true,
				bufferData:'',
				saveFlag:false,

				  // 打印
				  looptime: 0,
				currentTime: 1,
				lastData: 0,
				oneTimeData: 0,
				buffSize: [],
				buffIndex: 0,
				printNum: [],
				printNumIndex: 0,
				printerNum: 1,
				currentPrint: 1,
				isLabelSend: false,
				isQuery: false,
				canvasWidth: 100,
				canvasHeight: 100,
				jpgWidth: 200,
				jpgHeight: 200,
				role: "",
				roleList: {},
				btnFlag: false,
				printArr: [],
				title: "",
				ids: "",
				ok_printer_sn: "",
				ydytitle: "",
				pz: 0,
				projectName: "",
				deviceId: '',
			}
		},
		onLoad() {
			this.deviceId = app.globalData.BLEInformation.deviceId
			if(!app.globalData.BLEInformation.deviceId) {
				uni.showModal({
					title:'提示',
					content:'蓝牙未连接,请先连接',
					success: (r) => {
						
					}
				})
			}
			this.url = uni.getStorageSync('url') == '' ? this.websiteUrl : uni.getStorageSync('url')
			this.uid = uni.getStorageSync('uid')
			this.uname = uni.getStorageSync('uname')
			TTSSpeech.init((status) => {
				if (status === 0) {
					// console.log('引擎初始化成功')
				}
			}, 'com.iflytek.speechcloud')
			var _this = this
			uni.$off('scancodedate')
			uni.$on('scancodedate', function(content) {
				// if (_this.tm != content) {
				console.log(content, 'content')
				if (_this.arr.some(item =>item.barcode == content)) {
					uni.showToast({
						title: '此条码已扫描!',
						icon: 'none',
						duration: 3000
					})
					TTSSpeech.speak({
						text: '此条码已扫描'
					})
					return
				}
				uni.request({
					url: `http://${_this.url}/bService.asmx/GetCpzxdBarcode`,
					method: 'GET',
					dataType: 'json',
					data: {
						barcode: content
					},
					success: (r) => {
						console.log(r);
						if (r.data.code == 200) {
							
							let temp = r.data.data[0]
							_this.tm = temp.barcode
							_this.sl = temp.sl
							_this.bbreed = temp.bbreed
							_this.color = temp.color
							_this.chima = temp.chima
							uni.showToast({
								title: r.data.msg,
								icon: 'none',
								duration: 3000
							})
							TTSSpeech.speak({
								text: r.data.msg,
							})
						} else {
							uni.showToast({
								title: r.data.msg,
								icon: 'none',
								duration: 3000
							})
							TTSSpeech.speak({
								text: r.data.msg,
							})
						}
					},
					complete: (r) => {
						console.log(r.statusCode != 200)
						if (r.statusCode != 200) {
							uni.showToast({
								title: '网络请求失败!',
								icon: 'none',
								duration: 3000
							})
						}
					}
				})
			})

		},
		onReady() { // 打印使用
    var list = [];
    var numList = [];
    var j = 0;

    for (var i = 20; i < 200; i += 10) {
      list[j] = i;
      j++;
    }

    for (var i = 1; i < 10; i++) {
      numList[i - 1] = i;
    }

    this.setData({
      buffSize: list,
      oneTimeData: list[0],
      printNum: numList,
      printerNum: numList[0],
    });
  },
		computed: {
			sum() {
				return this.arr.length
			}
		},
		methods: {
			saveInfo() {

				var _this = this
				if(_this.arr.length == 0){
					uni.showToast({
						title: '请先扫条码',
						icon: 'none',
						duration: 3000
					})
					TTSSpeech.speak({
						text: '请先扫条码',
					})
					return
				}
				_this.printSingleItem()
				console.log('=== arr', _this.arr)
			},
			getDate(){
				const today = new Date();  
				const month = today.getMonth() + 1;  
				const day = today.getDate();
				const formattedMonth = month < 10 ? '0' + month : month;  
				const formattedDay = day < 10 ? '0' + day : day;  
				return month + '-' + day
			},
		
			printSingleItem() {  
				var _this = this
				var date = _this.getDate()
				// 500 * 1000
				// let strCmd = blesdk.CreatCPCLPage(400, 800, 1, 0);  
			    // strCmd += blesdk.addCPCLBox(20, 20, 380, 740, 1);  
			    // strCmd += blesdk.addCPCLSETMAG(2, 2);  
				// strCmd += blesdk.addCPCLBarCode(40,500,'128',90,1,1,20,_this.arr[index].barcode)
				// strCmd += blesdk.addCPCLText(370,30,'24',2,3,'货号');
				// strCmd += blesdk.addCPCLText(370,180,'24',3,3,'' + _this.arr[index].bbreed);
				// strCmd += blesdk.addCPCLText(310,30,'24',5,3,'颜色');
				// strCmd += blesdk.addCPCLText(310,180,'24',6,3,'' + _this.arr[index].color);
				// strCmd += blesdk.addCPCLText(310,410,'24',7,3,'日期');
				// strCmd += blesdk.addCPCLText(310,540,'24',9,3,date);
				// strCmd += blesdk.addCPCLText(250,30,'24',7,3,'尺码');
				// strCmd += blesdk.addCPCLText(250,180,'24',9,3,'' + _this.arr[index].chima);
				// strCmd += blesdk.addCPCLText(250,410,'24',7,3,'数量');
				// strCmd += blesdk.addCPCLText(250,540,'24',9,3,'' + _this.arr[index].sl);
				// strCmd += blesdk.addCPCLText(190,30,'24',7,3,'定型');
				// strCmd += blesdk.addCPCLText(190,180,'24',9,3,'' + _this.uname);
				// strCmd += blesdk.addCPCLText(190,410,'24',7,3,'拼缝');
				// strCmd += blesdk.addCPCLText(190,540,'24',9,3,'' + _this.uname);


				// 70 * 80
				var _this = this
				var command = tsc.jpPrinter.createNew();
				_this.arr.forEach((item, index) => {
					command.setCls();
					command.setSize(80, 70);
					command.setGap(0);
					command.setCls();
					command.setBox(20, 20, 600, 520, 1); //绘制一个边框
					command.setText(30, 30, "TSS24.BF2", 0, 2, 2, `货号 ${_this.arr[index].bbreed}`);
					command.setText(30, 80, "TSS24.BF2", 0, 2, 2, `颜色 ${_this.arr[index].color}`);
					command.setText(30, 130, "TSS24.BF2", 0, 2, 2, `日期 ${date}`);
					command.setText(30, 180, "TSS24.BF2", 0, 2, 2, `尺码 ${_this.arr[index].chima}`);
					command.setText(30, 230, "TSS24.BF2", 0, 2, 2, `数量 ${_this.arr[index].sl}`);

					command.setBarCode(90, 400, "128M", 70, 1, 0, 2, 4, _this.arr[index].barcode); // 绘制条码
					command.setPagePrint(); //执行打印指令
					this.setData({
						isLabelSend: true,
					});
				})
				
				setTimeout(() => {
					this.prepareSend(command.getData());
				}, 500);
			},
			save(){
				if(this.tm == ''){
					uni.showToast({
						title: '请先扫条码',
						icon: 'none',
						duration: 3000
					})
					TTSSpeech.speak({
						text: '请先扫条码'
					})
					return
				}
				let data = {
					barcode: this.tm,
					username:this.uid,
					sl:this.sl
				}
				console.log(data);
				uni.request({
					url: `http://${this.url}/bService.asmx/CpzxdBarcode_ck`,
					method: 'GET',
					dataType: 'json',
					data: {
						barcode: this.tm,
						username:this.uname,
						sl:this.sl
					},
					success: (r) => {
						console.log(r);
						if(r.data.code == 200){
							let temp = r.data.data
							temp.forEach(item=>this.arr.push(item))
							this.tm = ''
							this.bbreed = ''
							this.color = ''
							this.chima = ''
							this.sl = ''
						}
						uni.showToast({
							title: r.data.msg,
							icon: 'none',
							duration: 3000
						})
						TTSSpeech.speak({
							text: r.data.msg,
						})
					},
					complete: (r) => {
						if (r.statusCode != 200) {
							uni.showToast({
								title: '网络请求失败!',
								icon: 'none',
								duration: 3000
							})
						}
						this.saveFlag = false
					}
				})
			},

			prepareSend: function (buff) {
			//准备发送，根据每次发送字节数来处理分包数量
			//console.log(buff)
			var that = this;
			var time = that.oneTimeData;
			var looptime = parseInt(buff.length / time);
			var lastData = parseInt(buff.length % time); //console.log(looptime + "---" + lastData)

			that.setData({
				looptime: looptime + 1,
				lastData: lastData,
				currentTime: 1,
			});
			that.Send(buff);
			},
			Send: function (buff) {
				//分包发送
				var that = this;
				var currentTime = that.currentTime;
				var loopTime = that.looptime;
				var lastData = that.lastData;
				var onTimeData = that.oneTimeData;
				var printNum = that.printerNum;
				var currentPrint = that.currentPrint;
				var buf;
				var dataView;

				if (currentTime < loopTime) {
					buf = new ArrayBuffer(onTimeData);
					dataView = new DataView(buf);

					for (var i = 0; i < onTimeData; ++i) {
					dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
					}
				} else {
					buf = new ArrayBuffer(lastData);
					dataView = new DataView(buf);

					for (var i = 0; i < lastData; ++i) {
					dataView.setUint8(i, buff[(currentTime - 1) * onTimeData + i]);
					}
				} //console.log("第" + currentTime + "次发送数据大小为：" + buf.byteLength)

				uni.writeBLECharacteristicValue({
					deviceId: that.deviceId,
					serviceId: "49535343-FE7D-4AE5-8FA9-9FAFD205E455",
					characteristicId: "49535343-8841-43F4-A8D4-ECBE34729BB3",
					value: buf,
					success: function (res) {
					if (currentPrint == printNum) {
						uni.showToast({
						title: "已打印第" + currentPrint + "张成功",
						});
					} //console.log(res)
					},
					fail: function (e) {
					uni.showToast({
						title: "打印第" + currentPrint + "张失败",
						icon: "none",
					}); //console.log(e)
					},
					complete: function () {
					currentTime++;

					if (currentTime <= loopTime) {
						that.setData({
						currentTime: currentTime,
						});
						that.Send(buff);
					} else {
						// wx.showToast({
						//   title: '已打印第' + currentPrint + '张',
						// })`
						if (currentPrint == printNum) {
						that.setData({
							looptime: 0,
							lastData: 0,
							currentTime: 1,
							isLabelSend: false,
							currentPrint: 1,
						});
						} else {
						currentPrint++;
						that.setData({
							currentPrint: currentPrint,
							currentTime: 1,
						});
						that.Send(buff);
						}
					}
					},
				});
				},
		}
	}
</script>

<style>
	.cell{display: flex;align-items: center;width: 100%;padding: 20rpx 0;}
	.cell-item{display: flex;align-items: center;width: 50%;}
	.cell-item text {width: 120rpx;}
	.cell-item input {border: 1px solid #ccc;width: 60%;}
</style>